package com.powernode.shop.controller;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashSet;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/12
 */

@RestController
public class FileController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    // nginx端口为8888
    @Value("${resources.url}")
    private String host;

    /**
     * 接收文件上传统一路径
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/admin/file/upload/element")
    public ResponseEntity<String> fileUpload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        // 获得文件后缀
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        long size = file.getSize();
        if (size < 0) throw new IllegalStateException("上传文件不能为空");
        // 上传文件到fastdfs 返回文件访问路径
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), size, filenameExtension, new HashSet<>());
        System.out.println("******************storePath = " + storePath);
        // 拼接host
        return ResponseEntity.ok(host + storePath.getFullPath());
    }


}
